package com.powerunion.datacollection.web.struts;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.powerunion.datacollection.service.CollectionTaskInstanceManager;
import com.powerunion.datacollection.transaction.Transaction;
import com.powerunion.datacollection.transaction.TransactionHelper;
import com.powerunion.util.log.LogHelper;

public class CollectionTaskInstanceAction extends BaseAction {

	private static final Logger logger = LogHelper.getInstance().getLogger(CollectionTaskInstanceAction.class);
	private CollectionTaskInstanceManager ctManager = null;
	
	public CollectionTaskInstanceAction() {
		super();
		this.ctManager = new CollectionTaskInstanceManager();
	}
	
	public void finalize() throws Throwable {
		this.ctManager = null;
		super.finalize();
	}

	public ActionForward save (ActionMapping mapping,ActionForm form,
			HttpServletRequest request,HttpServletResponse response)
	        throws Exception {
		
		String saveStr = request.getParameter("formData");
		String userCode = request.getRemoteUser();
		Transaction transaction = null;
		try {
			transaction = TransactionHelper.getTransaction();
			transaction.begin();
			logger.debug("任务实例信息定义:"+saveStr);
			response.setContentType("text/json;charset=utf-8");
			String result = this.ctManager.save(saveStr,userCode);
	        if(StringUtils.isEmpty(result)) {
	        	response.getWriter().write("{success:true}");
	        }else{
	        	response.getWriter().write("{failure:true,data:'"+result+"'}");
	        }
			
			transaction.commit();
		} catch (Exception e) {
			logger.error("", e);
			try {
				transaction.rollback();
			} catch (Exception e1) {
				logger.error("", e1);
				throw e;
			} finally {
				transaction = null;
				response.getWriter().write("{failure:true}");
			}
		}

		return null;
	}
	
	public ActionForward list(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		
        String startStr = request.getParameter("start")==null?"0":request.getParameter("start");
        String limitStr = request.getParameter("limit")==null?"28":request.getParameter("limit");
        
        int start = Integer.parseInt(startStr);
        int limit = Integer.parseInt(limitStr);
        
        String userCode = request.getRemoteUser();
        
		String result = this.ctManager.getCollectionTaskInstances(start,limit,userCode); 
		logger.debug("CollectionTasks:"+result);
		response.setContentType("text/json;charset=utf-8");
		try{
			response.getWriter().print(result);
		}catch(Exception e) {
			logger.error("输出json失败",e);
			return null;
		}
		return null;
	}
	
	public ActionForward delete(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		
		String[] ids = StringUtils.split(request.getParameter("codes"), ",");
		
		Transaction transaction = null;

		response.setContentType("text/json;charset=utf-8");
		try {
			transaction = TransactionHelper.getTransaction();
			transaction.begin();

			boolean flag = this.ctManager.delete(ids);

			if (flag == true) {
				response.getWriter().print("{success:true}");
			} else {
				response.getWriter().write("{failure:true}");
			}
			transaction.commit();

		} catch (Exception e) {
			logger.error("", e);
			try {
				transaction.rollback();
			} catch (Exception e1) {
				logger.error("", e1);
				throw e;
			} finally {
				transaction = null;
				response.getWriter().write("{failure:true}");
			}
		}
		return null;
	}
	
	public ActionForward startupTask(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		
		String taskInfo = request.getParameter("formData");
		logger.debug("startupTask taskInfo:"+taskInfo);
		String userCode = request.getRemoteUser();
		
		Transaction transaction = null;

		response.setContentType("text/json;charset=utf-8");
		try {
			transaction = TransactionHelper.getTransaction();
			transaction.begin();

			String result = this.ctManager.startupTask(taskInfo,userCode);
logger.debug("startupTask result:"+result);
			if (!StringUtils.isEmpty(result) && result.equals("success")) {
				response.getWriter().print("{success:true,data:''}");
			} else {
				response.getWriter().write("{failure:true,data:'"+result+"'}");
			}
			transaction.commit();
		} catch (Exception e) {
			logger.error("", e);
			try {
				transaction.rollback();
			} catch (Exception e1) {
				logger.error("", e1);
				throw e;
			} finally {
				transaction = null;
				response.getWriter().write("{failure:true}");
			}
		}
		return null;
	}
	
	public ActionForward suspendTask(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		
		String procId = request.getParameter("procId");
		String taskId = request.getParameter("taskId");
		
		Transaction transaction = null;

		try {
			transaction = TransactionHelper.getTransaction();
			transaction.begin();

			boolean flag = this.ctManager.suspendTask(procId,taskId);

			if (flag) {
				this.renderSuccssJson(response);
			} else {
				this.renderFAILUREJson(response);
			}
			transaction.commit();
		} catch (Exception e) {
			logger.error("", e);
			try {
				transaction.rollback();
			} catch (Exception e1) {
				logger.error("", e1);
				throw e;
			} finally {
				transaction = null;
				this.renderFAILUREJson(response);
			}
		}
		return null;
	}
	
	public ActionForward resumeTask(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		
		String procId = request.getParameter("procId");
		String taskId = request.getParameter("taskId");
		
		Transaction transaction = null;

		try {
			transaction = TransactionHelper.getTransaction();
			transaction.begin();

			boolean flag = this.ctManager.resumeTask(procId, taskId);

			if (flag) {
				this.renderSuccssJson(response);
			} else {
				this.renderFAILUREJson(response);
			}
			transaction.commit();
		} catch (Exception e) {
			logger.error("", e);
			try {
				transaction.rollback();
			} catch (Exception e1) {
				logger.error("", e1);
				throw e;
			} finally {
				transaction = null;
				this.renderFAILUREJson(response);
			}
		}
		return null;
	}

}
